package com.king.wxpay.util;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Bean工具类
 * @author taomk
 * @version 1.0
 * @since 15-7-10 下午4:08
 */
public class BeanUtil {

	private static final Map<Class, PropertyDescriptor[]> map = new ConcurrentHashMap<Class, PropertyDescriptor[]>();

	public static PropertyDescriptor[] getPropDescs(Class c) {
		try {
			PropertyDescriptor[] propDescs = map.get(c);
			if (propDescs == null) {
				BeanInfo info = Introspector.getBeanInfo(c, Introspector.IGNORE_ALL_BEANINFO);
				propDescs = info.getPropertyDescriptors();
				map.put(c, propDescs);
			}
			return propDescs;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void copyAttrs(Object src, Object dest) {
		try {
			PropertyDescriptor[] srcDescs = getPropDescs(src.getClass());//srcinfo.getPropertyDescriptors();
			PropertyDescriptor[] destDescs = getPropDescs(dest.getClass());//destinfo.getPropertyDescriptors();
			for (PropertyDescriptor srcProp : srcDescs) {
				String name = srcProp.getName();
				if ("class".equals(name))
					continue;
				for (PropertyDescriptor destProp : destDescs) {
					if (name.equals(destProp.getName())) {
						Method rm = srcProp.getReadMethod();
						Method wm = destProp.getWriteMethod();
						if (rm == null || wm == null)
							continue;
						Object v = rm.invoke(src);
						wm.invoke(dest, v);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
